package com.one.blocks.mvc.valid;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.cfg.ConstraintMapping;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;

/**
 * @author <a href="mailto:idler41@163.com">linfuxin</a> created by 2022-12-11 15:01:33
 */
@Configuration
public class ValidatorConfig {

    @Bean
    public Validator validator(AutowireCapableBeanFactory springFactory, List<ValidatorProvider> validatorProviderList) {
        HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();
        ConstraintMapping globalConstraintMapping = configuration.createConstraintMapping();
        for (ValidatorProvider validatorProvider : validatorProviderList) {
            validatorProvider.additionConstraintMapping(globalConstraintMapping);
        }
        configuration.addMapping(globalConstraintMapping);
        try (ValidatorFactory factory = configuration
                .failFast(true)
                // 解决 SpringBoot 依赖注入问题
                .constraintValidatorFactory(new SpringConstraintValidatorFactory(springFactory))
                .buildValidatorFactory()
        ) {
            return factory.getValidator();
        }
    }
}
